#include <iostream>
#include <string>
#include "easysock.hpp"
#include "protocol.hpp"
#include "task.hpp"

void usage(const std::string& proc)
{
    std::cout << "Uasge:\n\t" << proc << " svr_ip svr_port\n" << std::endl;
}

const std::string ops = "+-*/%";

class calc_client : public inet::tcp::client
{
public:
    calc_client(const std::string& sip, uint16_t sport) : client(sip, sport) {}

    ~calc_client() {}

    void start()
    {
        while (true)
        {
            int x = rand() % 10;
            int y = rand() % 10;
            char op = ops[rand() % ops.size()];

            proto::request req(x, op, y);
            std::string reqstr = req.serialize();
            send(reqstr);

            std::string rspstr;
            ssize_t s = recv(&rspstr, 1024);
            if (s > 0)
            {
                proto::response rsp;
                rsp.deserialize(rspstr);

                if (rsp._st == 0) std::cout << light_green "ok: "  << rsp._res << none << std::endl;
                else              std::cout << light_red   "error"             << none << std::endl;
            }
            else 
            {
                break;
            }
        }
    }

};


int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    std::string sip = argv[1];
    uint16_t sport = std::stoi(argv[2]);

    srand(time(0));

    std::unique_ptr<calc_client> tcli(new calc_client(sip, sport));
    tcli->start();

    return 0;
}
